import {Controller, Render, Get, Param, Session, UseBefore, Res } from "routing-controllers";
import { utils } from "../../utils/utils";
import { Service, Inject } from "typedi";
import { CarServiceImpl } from "../../service/impl/CarServiceImpl";
import { CheckLoginMiddleware } from "../../middleware/CheckLoginMiddleware";
import { Alipay } from "../../plugins/alipay";

/**
 * 获取购物车数据，计算商品总价，配置使用支付宝支付。
 */
@Service()
@Controller()
@UseBefore(CheckLoginMiddleware)
export class CarControllerHome {
	
	@Inject()
	private carServiceImpl: CarServiceImpl;
	
	@Inject()
	private aliPay: Alipay;
	
	@Get("/car")
	@Render("home/page/car")
	public async myCar (@Session() session) {
		
		let OrderNumber: number = new Date().valueOf();
		
		// 根据用户id 和 订单状态查询未完成订单，同时为未完成订单更新商户订单号
		let listData = await this.carServiceImpl.getCarList(session.user.objectId, OrderNumber),
				totalAmount = 0;
		
		// 计算所有未完成的订单的总价
		listData.forEach(val => totalAmount+= val['coursePrice']);

		// 配置支付参数
		this.aliPay.setFormData({
			outTradeNo: OrderNumber,
			totalAmount: 0.01,
			body: session.user.objectId
		});
		
		return {
			title: utils.titleName("购物车"),
			isShowAction: {
				header: true,
				footer: true
			},
			banner: {
				bannerTitle: "购物车",
				bannerUrl: "/img/banner_4.jpg"
			},
			cartList: listData,
			payUrl: await this.aliPay.startPay(), // 向前端传递支付的 a 标签地址
			login: session.user ? session.user : false
		}
	}
}